package config

import (
	"bufio"
	"fmt"
	"os"
	"strings"
)

var SERVER_URL = "http://127.0.0.1:8080"

func LoadConfig(filename string) (map[string]string, error) {

	config := make(map[string]string)

	file, err := os.Open(filename)
	if err != nil {
		return nil, err
	}
	defer file.Close()

	scanner := bufio.NewScanner(file)
	for scanner.Scan() {
		line := scanner.Text()
		line = strings.TrimSpace(line)

		// 忽略空行和注释行
		if len(line) == 0 || strings.HasPrefix(line, "#") {
			continue
		}

		// 分割键值对
		parts := strings.SplitN(line, "=", 2)
		if len(parts) != 2 {
			return nil, fmt.Errorf("invalid config line: %s", line)
		}

		key := strings.TrimSpace(parts[0])
		value := strings.TrimSpace(parts[1])

		config[key] = value
	}

	if err := scanner.Err(); err != nil {
		return nil, err
	}

	return config, nil
}

func InitConfig() {
	config, err := LoadConfig("config/config.ini")
	if err != nil {
		fmt.Println("Error loading config:", err)
		return
	}

	SERVER_URL = config["SERVER_URL"]
}
